package com.xtoneict.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xtoneict.auth.dto.*;
import com.xtoneict.auth.entity.*;
import com.xtoneict.auth.service.*;
import com.xtoneict.util.result.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hx
 * @since 2024-06-18
 */
@RestController
@RequestMapping("/auth/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private ILeaveDetailService leaveDetailService;
    @Autowired
    private IAttendanceService attendanceService;
    @Autowired
    private ILeaveCountService leaveCountService;
    @Autowired
    private IYearMonthTabService yearMonthService;
    @Autowired
    private ILeaveDayService leaveDayService;

    /**
     * 工时配比表上传
     * @param
     */
    @PostMapping("/timeSheet")
    @Transactional
    public Result addTimeSheet(@RequestBody TimeSheetDTO timeSheetDTO) {

        YearMonthTab yearMonthIn = yearMonthService.getByYearAndMonth(timeSheetDTO.getYear(),timeSheetDTO.getMonth());
        YearMonthTab yearMonth = new YearMonthTab();
        if(yearMonthIn == null){
            yearMonth.setThisYear(timeSheetDTO.getYear());
            yearMonth.setThisMonth(timeSheetDTO.getMonth());
            yearMonthService.save(yearMonth);
        }else {
            //查到了yearMonth，判断对应项目表是否存在
            LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Project::getYearMonthId, yearMonthIn.getYearMonthId());
            if (projectService.getMap(wrapper) != null){

                return Result.ok("该年月的项目表已存在");
            }else {
                yearMonth = yearMonthIn;
            }
        }

        List<WorkTimeDTO> workTimeDTOList = timeSheetDTO.getList();

        for (WorkTimeDTO workTimeDTO : workTimeDTOList) {

            Employee employeeIn = employeeService.getByName(workTimeDTO.getName());
            Employee employee = new Employee();
            if (employeeIn == null){
                BeanUtils.copyProperties(workTimeDTO, employee);
                int depId = departmentService.getIdByName(workTimeDTO.getDepartment());
                employee.setDepId(depId);
                employee.setStatus(Employee.ON_DUTY);
                employeeService.save(employee);
            }else {
                employee = employeeIn;
            }

            for (Project project : workTimeDTO.getProjects()) {
                project.setEmployeeId(employee.getEmployeeId());
                project.setYearMonthId(yearMonth.getYearMonthId());
                projectService.save(project);
            }
        }
        return Result.ok();
    }


    @PostMapping("/attendance")
    @Transactional
    public Result Attendance(@RequestBody AttenDTO attenDTO) {

        YearMonthTab yearMonthIn = yearMonthService.getByYearAndMonth(attenDTO.getYear(),attenDTO.getMonth());
        YearMonthTab yearMonth = new YearMonthTab();
        if(yearMonthIn == null){
            yearMonth.setThisYear(attenDTO.getYear());
            yearMonth.setThisMonth(attenDTO.getMonth());
            yearMonthService.save(yearMonth);
        }else {
            //查到了yearMonth，判断对应考勤表是否存在
            LambdaQueryWrapper<Attendance> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Attendance::getYearMonthId, yearMonthIn.getYearMonthId());

            List<Attendance> list = attendanceService.list(wrapper);
            if (list != null && !list.isEmpty()){
                return Result.ok("该年月的考勤表已存在");
            }else {
                yearMonth = yearMonthIn;
            }
        }

        List<AttendanceDTO> attendanceDTOList = attenDTO.getList();

        if(attendanceDTOList == null){
            return Result.fail("考勤表为空");
        }

        for (AttendanceDTO attendanceDTO : attendanceDTOList) {

            Employee employee = employeeService.getByName(attendanceDTO.getName());

            // 检查employee是否为null
            if (employee == null) {
                return Result.fail("员工 " + attendanceDTO.getName() + "不存在");
            }

            Attendance attendance = new Attendance();
            BeanUtils.copyProperties(attendanceDTO, attendance);
            attendance.setEmployeeId(employee.getEmployeeId());
            attendance.setYearMonthId(yearMonth.getYearMonthId());
            attendanceService.save(attendance);

            if(!attendanceDTO.getOtherLeaveDetails().isEmpty()){
                List<LeaveDetailHelper> leaveDetailHelpers = leaveDetailService.parseLeaveRecords(attendanceDTO.getOtherLeaveDetails());
                double leaveCountNum = 0;
                for (LeaveDetailHelper leaveDetailHelper : leaveDetailHelpers) {
                    if (leaveDetailHelper.getStatus()){
                        return Result.fail("考勤表备注栏存在格式错误");
                    }
                    LeaveDetail leaveDetail = new LeaveDetail();
                    BeanUtils.copyProperties(leaveDetailHelper, leaveDetail);
                    leaveDetail.setAttendanceId(attendance.getAttendanceId());
                    leaveDetailService.save(leaveDetail);
                    leaveCountNum += leaveDetail.getLeaveDays();

                    leaveDayService.saveLeaveDay(leaveDetail);
                }
                LeaveCount leaveCount = new LeaveCount();
                leaveCount.setEmployeeId(employee.getEmployeeId());
                leaveCount.setLeaveCount(leaveCountNum);
                leaveCountService.save(leaveCount);
            }

        }
        return Result.ok();
    }

    @PostMapping("/deleteTables")
    @Transactional
    public Result deleteTables(@RequestBody YearMonthDTO yearMonthDTO) {
        //删除yearMonth，级联删除project与attendance
        LambdaQueryWrapper<YearMonthTab> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(YearMonthTab::getThisMonth, yearMonthDTO.getMonth());
        wrapper.eq(YearMonthTab::getThisYear, yearMonthDTO.getYear());
        yearMonthService.remove(wrapper);
        return Result.ok();
    }

    @GetMapping("/getAllEmployees")
    public List<Employee> getAllEmployees(){
        return employeeService.list();
    }

}




